import { useEffect, useState, useRef } from 'react'

import { List, Typography, Input, DatePicker, ConfigProvider, Button, message, Dropdown } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';

// 引入中文语言包-日期选择器
import zhCN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';

//货物名称数据
import { productNameItems } from '../../constant/productNameData'
//经办人数据
import { handlePrersonData } from '../../constant/HandlePrersonData'

//网络
import { generateOrder } from '../../utils/axiosRequest/api.js'
import { development } from '../../utils/axiosRequest/RequestConfig.js'

import styles from './index.module.css'


function Mian_v2() {
    // 设置dayjs使用中文
    dayjs.locale('zh-cn');
    const iframeRef = useRef(null);
    const { Text } = Typography;
    const [messageApi, contextHolder] = message.useMessage();
    // 初始化9个商品数据
    const [products, setProducts] = useState(
        Array(9).fill().map(() => ({
            productName: '',
            productUnit: '斤',
            productQuantity: '',
            productPrice: '',
            productRemarks: ''
        }))
    );
    const [customerAddress, setCustomerAddress] = useState('')//客户地址
    const [deliveryTime, setDeliveryTime] = useState('')//送货时间
    const [handlerPerson, setHandlerPerson] = useState('')//经办人
    const [printBtnLoadState, setPrintBtnLoadState] = useState(false)//打印按钮加载状态

    //[]空数组相当于componentDidMount
    useEffect(() => {
        // 添加全局键盘事件监听->按上相键可以控制单元格选中状态
        const handleGlobalKeyDown = (e) => {
            if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
                const activeElement = document.activeElement;
                // 只处理输入框和日期选择器的导航
                if (activeElement.tagName === 'INPUT' || activeElement.classList.contains('ant-picker-input')) {
                    e.preventDefault();
                    const allInputs = Array.from(document.querySelectorAll('input, .ant-picker-input input'));
                    const currentIndex = allInputs.findIndex(input =>
                        input === activeElement || input.contains(activeElement)
                    );
                    if (currentIndex === -1) return;
                    let nextIndex = currentIndex;

                    switch (e.key) {
                        case 'ArrowUp':
                            nextIndex = Math.max(0, currentIndex - 5);
                            break;
                        case 'ArrowDown':
                            nextIndex = Math.min(allInputs.length - 1, currentIndex + 5);
                            break;
                        case 'ArrowLeft':
                            nextIndex = Math.max(0, currentIndex - 1);
                            break;
                        case 'ArrowRight':
                            nextIndex = Math.min(allInputs.length - 1, currentIndex + 1);
                            break;
                    }

                    if (nextIndex !== currentIndex && allInputs[nextIndex]) {
                        setTimeout(() => {
                            allInputs[nextIndex].focus();
                        }, 0);
                    }
                }
            }
        };
        document.addEventListener('keydown', handleGlobalKeyDown);
        return () => {
            document.removeEventListener('keydown', handleGlobalKeyDown);
        };
    }, []);

    function onChangeCustomerAddress(val) {
        let customerAddress = val.target.value
        setCustomerAddress(customerAddress);
    }

    function onChangeHandlerPerson(val) {
        let handlerPerson = val.target.value
        setHandlerPerson(handlerPerson);
    }

    const onDatePickerChange = (date, dateString) => {
        setDeliveryTime(dateString)
    };

    // 定义 clickProductName 函数
    const clickProductName = (itemIndex) => (e) => {
        const dataKey = e.key
        const selectedProductName = productNameItems[dataKey].name;
        handleFieldChange(itemIndex, 'productName', selectedProductName);
    };

    // 处理输入变化
    const handleFieldChange = (itemIndex, fieldName, value) => {
        setProducts(prev => {
            const newProducts = [...prev];
            newProducts[itemIndex] = {
                ...newProducts[itemIndex],
                [fieldName]: value
            };
            return newProducts;
        });
    };

    // 清空所有输入
    const clearAll = () => {
        setCustomerAddress('');
        setProducts(
            Array(9).fill().map(() => ({
                productName: '',
                productUnit: '斤',
                productQuantity: '',
                productPrice: '',
                productRemarks: ''
            }))
        );
        messageApi.success('货物已全部清空');
    };

    // 清空单行货物
    const clearProductItem = (itemIndex) => {
        setProducts(prev => {
            const newProducts = [...prev];
            newProducts[itemIndex] = {
                productName: '',
                productUnit: '斤',
                productQuantity: '',
                productPrice: '',
                productRemarks: ''
            };
            return newProducts;
        });
        messageApi.success('第' + (itemIndex + 1) + '行货物已清空');
    }

    // 选择制单人
    const clickHandlePrerson = ({ key }) => {
        const name = handlePrersonData[key].name
        setHandlerPerson(name)
    };

    // 提交表单
    const submitToServer = async () => {
        // 防止重复提交
        if (printBtnLoadState) {
            messageApi.error('正在打印中，请稍后...');
            return;
        }
        // 过滤掉完全为空的行
        const filteredProducts = products.filter(product =>
            product.productName.trim() !== '' &&
            product.productUnit.trim() !== '' &&
            product.productQuantity.trim() !== '' &&
            product.productPrice.trim() !== ''
        );
        // 设置加载状态
        setPrintBtnLoadState(true);
        try {
            const params = new Map();
            params.set('customerAddress', customerAddress);
            params.set('deliveryTime', deliveryTime);
            params.set('productList', filteredProducts);
            params.set('handlerPerson', handlerPerson);
            //处理响应
            const response = await generateOrder(params);
            const data = response.data;
            if (data.code === '000') {
                // 拿到文件名
                const pdfName = data.data.pdfName;
                // 直接打印PDF
                const printResponse = await fetch(development + `/preview/${pdfName}`);
                const blob = await printResponse.blob();
                const blobUrl = URL.createObjectURL(blob);
                // 使用固定的 iframe
                const iframe = iframeRef.current;
                // 创建 Promise 来等待 iframe 加载完成
                await new Promise((resolve, reject) => {
                    iframe.src = blobUrl;
                    iframe.onload = () => {
                        setTimeout(() => {
                            iframe.contentWindow?.print();
                            URL.revokeObjectURL(blobUrl); // 及时清理内存
                            resolve();
                        }, 500);
                    };
                    iframe.onerror = () => {
                        URL.revokeObjectURL(blobUrl);
                        reject(new Error('PDF加载失败'));
                    };
                });
            } else {
                messageApi.error(data.des);
            }
        } catch (error) {
            messageApi.error(error.message || '操作失败');
        } finally {
            setPrintBtnLoadState(false);
        }
    };

    return (
        <ConfigProvider locale={zhCN}>
            {contextHolder}
            <div className={styles.root_box} >
                <div className={styles.mian_box} >
                    <div className={styles.customer_address_box}>
                        <span>客户地址：</span>
                        <Input onPressEnter={submitToServer} onChange={onChangeCustomerAddress} value={customerAddress} className={styles.inp_customer_address} placeholder='请输入客户地址' allowClear={true} size="large" />
                        <span className={styles.text_customer_address} >制单人：</span>
                        <Dropdown trigger={['click']} menu={{ items: handlePrersonData, onClick: clickHandlePrerson }}>
                            <Input onPressEnter={submitToServer} onChange={onChangeHandlerPerson} value={handlerPerson} className={styles.inp_handler_person} placeholder='请输入制单人' allowClear={true} size="large" />
                        </Dropdown>
                        <span className={styles.text_customer_address} >送货日期：</span>
                        <DatePicker onChange={onDatePickerChange} placeholder={'请选择送货日期'} size={"large"} />
                    </div>
                    <List className={styles.lv_data}
                        size="small"
                        bordered
                        dataSource={products}
                        renderItem={(item, itemIndex) =>
                            <div className={styles.item_box}>
                                <Text keyboard>{itemIndex + 1}</Text>
                                <Dropdown trigger={['click']} menu={{ items: productNameItems, onClick: clickProductName(itemIndex) }}>
                                    <Input onPressEnter={submitToServer} value={item.productName} className={styles.inp_product_info} onChange={(e) => handleFieldChange(itemIndex, 'productName', e.target.value)} placeholder='货物名称' allowClear={true} size="large" />
                                </Dropdown>
                                <Input onPressEnter={submitToServer} value={item.productUnit} className={styles.inp_unit} onChange={(e) => handleFieldChange(itemIndex, 'productUnit', e.target.value)} placeholder='单位' allowClear={false} size="large" />
                                <Input onPressEnter={submitToServer} value={item.productQuantity} className={styles.inp_quantity} onChange={(e) => handleFieldChange(itemIndex, 'productQuantity', e.target.value)} placeholder='数量' allowClear={true} size="large" />
                                <Input onPressEnter={submitToServer} value={item.productPrice} className={styles.inp_price} onChange={(e) => handleFieldChange(itemIndex, 'productPrice', e.target.value)} placeholder='单价(元)' allowClear={true} size="large" />
                                <Input onPressEnter={submitToServer} value={item.productRemarks} className={styles.inp_remarks} onChange={(e) => handleFieldChange(itemIndex, 'productRemarks', e.target.value)} placeholder='备注' allowClear={true} size="large" />
                                <Button onClick={() => clearProductItem(itemIndex)} className={styles.btn_clear_item} icon={<DeleteOutlined />} variant="solid" color="cyan"></Button>
                            </div>}
                    />
                    <div className={styles.print_box}>
                        <Button loading={printBtnLoadState} onClick={submitToServer} className={styles.btn_print_product} type="primary">打印货单</Button>
                        <Button onClick={clearAll} className={styles.btn_clear_product} danger type="primary">全部清空</Button>
                    </div>
                    <iframe
                        title='PDF打印'
                        ref={iframeRef}
                        style={{ display: 'none', border: 'none' }}
                    />
                </div>
            </div>
        </ConfigProvider>
    )
}


export default Mian_v2

